package com.zhentao.service.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import com.zhentao.enty.QrCodeResponse;
import com.zhentao.mapper.UserMapper;
import com.zhentao.mapper.UserQrCodeMapper;
import com.zhentao.pojo.User;
import com.zhentao.pojo.UserQrCode;
import com.zhentao.service.LocalQrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class LocalQrCodeServiceImpl implements LocalQrCodeService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserQrCodeMapper userQrCodeMapper;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.url-prefix}")
    private String urlPrefix;

    @Value("${qrcode.base-url:http://localhost:8080/api/user/register?inviteCode=}")
    private String baseUrl;

    @Value("${qrcode.login-url:http://localhost:8080/app/user/login?inviteCode=}")
    private String loginUrl;

    @Value("${qrcode.width:300}")
    private int qrCodeWidth;

    @Value("${qrcode.height:300}")
    private int qrCodeHeight;

    @Override
    public QrCodeResponse generateUserQrCode(String userId) {
        return generateUserQrCode(userId, null);
    }

    @Override
    public QrCodeResponse generateUserQrCode(String userId, String scene) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        try {
            // 生成二维码内容 - 跳转到登录页面
            String qrCodeContent = loginUrl + userId;
            if (scene != null && !scene.trim().isEmpty()) {
                qrCodeContent += "&scene=" + scene;
            }

            // 生成二维码图片
            String fileName = userId + (scene == null ? "" : ("_" + scene)) + "_qrcode.png";
            String filePath = uploadPath + (uploadPath.endsWith("/") ? "" : "/") + fileName;

            // 确保目录存在
            File dir = new File(uploadPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成二维码
            generateQRCodeImage(qrCodeContent, qrCodeWidth, qrCodeHeight, filePath);

            log.info("二维码生成成功: {}", filePath);
            log.info("二维码内容: {}", qrCodeContent);

            // 生成访问URL
            String qrCodeUrl = urlPrefix + fileName;

            // 保存到数据库
            UserQrCode userQrCode = new UserQrCode();
            userQrCode.setUserId(userId);
            userQrCode.setQrCodeContent(qrCodeContent);
            userQrCode.setQrCodeUrl(qrCodeUrl);
            userQrCode.setQrCodePath(filePath);
            userQrCode.setStatus(1);
            userQrCodeMapper.insert(userQrCode);

            // 返回响应
            QrCodeResponse response = new QrCodeResponse();
            response.setUserId(userId);
            response.setQrCodeUrl(qrCodeUrl);
            response.setQrCodeContent(qrCodeContent);
            response.setInviteCode(userId);
            return response;

        } catch (Exception e) {
            log.error("生成二维码失败", e);
            throw new RuntimeException("生成二维码失败: " + e.getMessage());
        }
    }

    /**
     * 生成二维码图片
     */
    private void generateQRCodeImage(String text, int width, int height, String filePath)
            throws WriterException, IOException {

        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 2);

        // 创建二维码写入器
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        // 创建图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.BLACK);

        // 绘制二维码
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (bitMatrix.get(x, y)) {
                    graphics.fillRect(x, y, 1, 1);
                }
            }
        }

        graphics.dispose();

        // 保存图片
        ImageIO.write(image, "PNG", new File(filePath));
    }
}
